package com.srwl.mytx.fragment;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;

import androidx.appcompat.widget.Toolbar;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.snackbar.Snackbar;
import com.srwl.mytx.Constant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.adapter.TopicGridAdapter;
import com.srwl.mytx.contrack.GoodsConstrack;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Topic;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.TopicService;
import com.srwl.mytx.widget.NodataFooter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import me.dkzwm.widget.srl.MaterialSmoothRefreshLayout;
import me.dkzwm.widget.srl.SmoothRefreshLayout;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class TopicFragment extends BaseFragment {

    private static final String ARG_COLUMN_COUNT = "column-count";
    private static final String ARG_USER_ID = "uId";
    private static final String TAG = "TopicFragment";

    private int mColumnCount = 2;

    private List<Topic> topicList = new ArrayList<>();
    private TopicGridAdapter topicGridAdapter;
    private String uId;
    private MaterialSmoothRefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private boolean hasNextPage = true;
    private int from = 0;//数据开始索引
    private int page = 1;//mysql 分页的页数，从第一页开始
    private static final int SIZE = 10;//每页返回的数量
    private InteractionListener listener;
    private ItemClickListener itemClickListener;
    private LocalBroadcastManager broadcastManager;
    private BroadcastReceiver broadcastReceiver;
    private User loginUser;

    public TopicFragment() {
    }

    public static TopicFragment newInstance(int columnCount, String uId) {
        TopicFragment fragment = new TopicFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_COLUMN_COUNT, columnCount);
        args.putString(ARG_USER_ID, uId);
        fragment.setArguments(args);
        return fragment;
    }

    public static TopicFragment newInstance(int columnCount, String uId, boolean showWithDialog) {
        TopicFragment fragment = new TopicFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_COLUMN_COUNT, columnCount);
        args.putString(ARG_USER_ID, uId);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle arguments = getArguments();
        if (arguments != null) {
            mColumnCount = arguments.getInt(ARG_COLUMN_COUNT);
            uId = arguments.getString(ARG_USER_ID);
        }
        topicGridAdapter = new TopicGridAdapter(topicList, getActivity());
        topicGridAdapter.setListener(new TopicGridAdapter.InteractionListener() {
            @Override
            public boolean onItemClick(int position) {

                if (itemClickListener != null) {
                    itemClickListener.onItemClick(topicList.get(position));
                    return true;
                }
                return false;
            }

            @Override
            public void showProgress(boolean isShowProgress) {
                if (listener != null) {
                    listener.showLoading(isShowProgress);
                }
            }

            @Override
            public void showToast(String content) {
                Snackbar.make(recyclerView, content, Snackbar.LENGTH_LONG).show();
            }

            @Override
            public void onDeleteTopic(int position) {

            }
        });

        registerBroadcastReceiver();
        loginUser = UserProfileManager.getInstance().getLoginUserInfo();
        //loadDataFromMysql();
    }

    private void registerBroadcastReceiver() {
        broadcastManager = LocalBroadcastManager.getInstance(getContext());
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constant.ACTION_TOPIC_EDIT_CHANGED);
        intentFilter.addAction(Constant.ACTION_TOPIC_MANAGER_REMOVE);
        intentFilter.addAction(Constant.ACTION_TOPIC_MANAGER_TRANSFER);
        broadcastReceiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                switch (action) {
                    //刷新动态发布的主题信息
                    case Constant.ACTION_TOPIC_EDIT_CHANGED: {
                        Topic updateTopic = intent.getParcelableExtra(Constant.EXTRA_INFO_TOPIC);
                        refresh(updateTopic);
                        break;
                    }
                    case Constant.ACTION_TOPIC_MANAGER_REMOVE://管理员移除，或者是主动放弃管理员权限
                    case Constant.ACTION_TOPIC_MANAGER_TRANSFER://当管理员移交后，个人主题记录页面，不再显示，那个主题已经不再属于自己了
                        Topic deleteTopic = intent.getParcelableExtra(Constant.EXTRA_INFO_TOPIC);
                        topicDelete(deleteTopic);
                        break;
                }
            }
        };
        broadcastManager.registerReceiver(broadcastReceiver, intentFilter);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_topic_list, container, false);

        // Set the adapter

        Context context = view.getContext();
        refreshLayout = view.findViewById(R.id.refresh_layout);
        recyclerView = view.findViewById(R.id.rv_topic);
        if (listener != null) {
            listener.showLoading(true);
        }
        //loadData();
        if (isTempUser()) {
            topicGridAdapter.showNoDataView();
        } else {
            loadDataFromMysql(true, false);
        }

        refreshLayout.setEnableOverScroll(true);//关掉会出现，item 重建后，第一次点击事件无须，会被refreshLayout 拦截掉
        refreshLayout.setDisableRefresh(true);
        refreshLayout.setDisableLoadMore(false);
        refreshLayout.setOnLoadMoreScrollCallback(new SmoothRefreshLayout.OnLoadMoreScrollCallback() {
            @Override
            public void onScroll(View content, float delta) {

                recyclerView.scrollBy(0, (int) delta);
            }
        });
        refreshLayout.setOnRefreshListener(new SmoothRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefreshing() {

                from = 0;
                page = 1;
                // loadData();
                if (!isTempUser()) {
                    loadDataFromMysql(false, true);
                }
            }

            @Override
            public void onLoadingMore() {
                if (hasNextPage && !isTempUser()) {
                    // lstVisibleItemPosition = linearLayoutManager.findLastVisibleItemPosition();
                    //  loadData();
                    loadDataFromMysql(false, false);
                } else {
                    refreshLayout.refreshComplete();
                    Log.d(TAG, "onRefreshBegin: 没有更多数据了");
                }
            }

        });

        GridLayoutManager gridLayoutManager = new GridLayoutManager(context, mColumnCount);
        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int i) {
                if (topicList.size() == 0) {
                    return mColumnCount;
                }

                return 1;
            }
        });
        recyclerView.setLayoutManager(gridLayoutManager);
        recyclerView.setAdapter(topicGridAdapter);

        return view;
    }

    @Override
    public void onStart() {
        super.onStart();
//        if (showWithDialog) {
//            Window win = getDialog().getWindow(); // 一定要设置Background，如果不设置，window属性设置无效
//            win.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
//            DisplayMetrics dm = new DisplayMetrics();
//            getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
//            WindowManager.LayoutParams params = win.getAttributes();
//            // params.gravity = Gravity.CENTER; // 使用ViewGroup.LayoutParams，以便Dialog 宽度充满整个屏幕
//            params.width = ViewGroup.LayoutParams.MATCH_PARENT;
//            params.height = ViewGroup.LayoutParams.MATCH_PARENT;
//            win.setAttributes(params);
//        }
    }

    public void setDataSet(List<Topic> topicList) {

        this.topicList.addAll(topicList);
        topicGridAdapter.notifyDataSetChanged();

    }

    private void loadDataFromMysql(boolean isFirst, boolean isRefresh) {
        if (!Helper.getInstance().isNetworkConnected()) {
            if (!isFirst) refreshLayout.refreshComplete();
            showToast_v1(getString(R.string.network_anomalies));
            return;
        }
        Map<String, Object> info = new HashMap<>();
        info.put("status", GoodsConstrack.GOODS_STATUS_NORMAL);
        info.put("uId", uId);
        info.put("page", page);
        info.put("size", SIZE);

        RetrofitManager.getInstance().createRequest(TopicService.class)
                .getTopicByUid(info)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        if (isFirst && listener != null) {
                            listener.showLoading(false);
                        } else {
                            refreshLayout.refreshComplete();
                        }

                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            if (page == 1) {
                                topicGridAdapter.showErrorView();
                            }
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            if (page == 1) {
                                topicGridAdapter.showErrorView();
                            }
                            return;
                        }
                        JSONObject body = (JSONObject) result.getData();
                        Log.d(TAG, "onResponse: 获取Topic完成" + body.toJSONString());
                        List<Topic> topics = body.getJSONArray("list").toJavaList(Topic.class);

                        hasNextPage = body.getBoolean("hasNextPage");
                        if (!hasNextPage && isAdded()) {
                            refreshLayout.postDelayed(() -> {
                                if (getActivity() != null) {
                                    refreshLayout.setFooterView(new NodataFooter(getActivity()));
                                }
                            }, 1000);
                        }
                        if (topics == null) {
                            return;
                        }
                        if (isRefresh) {
                        }

                        if (topics.size() != 0) {
                            topicList.addAll(topics);
                            topicGridAdapter.showNormalView((page-1)*SIZE,SIZE);
                            page++;
                        } else if (page == 1) {
                            topicGridAdapter.showNoDataView();
                        }
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        if (isFirst && listener != null) {
                            listener.showLoading(false);
                        } else {
                            refreshLayout.refreshComplete();
                        }
                        if (page == 1) {
                            topicGridAdapter.showErrorView();
                        }

                        Log.e(TAG, "onFailure: " + t.getMessage());
                    }
                });
    }

    /**
     * 获取用户发布的各种数据
     */
    private void loadData() {

        Map<String, Object> info = new HashMap<>();
        info.put("status", Constant.TOPIC_STATUS_NORMAL);
        info.put("uId", uId);
        info.put("from", from);
        info.put("size", SIZE);
        RetrofitManager.getInstance().createRequest(TopicService.class)
                .searchByUid(info)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        if (listener != null) {
                            listener.showLoading(false);
                        }
                        refreshLayout.refreshComplete();
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
//                            if (from == 1) {
//                                showErrorImage();
//                            }
                            topicGridAdapter.showErrorView();
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, result.getMsg());
//                            if (from == 1) {
//                                showErrorImage();
//                            }
                            topicGridAdapter.showErrorView();
                            return;
                        }
                        JSONObject jsonObject = (JSONObject) result.getData();
                        Log.d(TAG, "onResponse: 获取动态发布信息完成：" + jsonObject);
                        List<Topic> topics = JSONObject.parseArray(jsonObject.getString("hits"), Topic.class);
//                        if ((topics == null || topics.size() == 0) && from == 1) {
//                            showErrorImage();
//                        }
                        if (topics.size() > 0) {
                            topicList.addAll(topics);
                            topicGridAdapter.showNormalView();

                            if (topics.size() < SIZE) {
                                hasNextPage = false;
                                refreshLayout.postDelayed(() -> {
                                    if (getActivity() != null) {
                                        refreshLayout.setFooterView(new NodataFooter(getActivity()));
                                    }
                                }, 1000);
                            }

                            from += SIZE;
                        } else if (from == 1) {
                            topicGridAdapter.showNoDataView();
                        }
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        if (listener != null) {
                            listener.showLoading(false);
                        }

                        refreshLayout.refreshComplete();
                        topicGridAdapter.showErrorView();
                        Log.e(TAG, "onFailure: " + t.getMessage());
                    }
                });

    }


    public void setListener(InteractionListener listener) {
        this.listener = listener;
    }


    public void updateTopicMoney(Topic topic) {

    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK || data == null) {
            return;
        }
        Topic updateTopic = data.getParcelableExtra(Constant.EXTRA_INFO_TOPIC);
        if (updateTopic == null) {
            return;
        }
        for (int i = 0; i < topicList.size(); i++) {
            Topic topic = topicList.get(i);
            if (TextUtils.equals(updateTopic.getId(), topic.getId())) {
                //主题被删除或者管理员移交给别人了，都不应该继续显示到个人主题记录页面
                if (data.getBooleanExtra(Constant.EXTRA_TOPIC_DELETE, false) || data.getBooleanExtra(Constant.EXTRA_TOPIC_TRANSFER, false)) {
                    topicList.remove(i);
                    topicGridAdapter.notifyItemRemoved(i);
                    topicGridAdapter.notifyItemRangeChanged(i, topicList.size() - i);
                } else if (data.getBooleanExtra(Constant.EXTRA_TOPIC_CHANGE, false)) {//主题改变，这个对应的可能很多，比如评论数量增加，
                    topicList.remove(i);
                    topicList.add(i, updateTopic);
                    topicGridAdapter.notifyItemChanged(i);
                }
                break;
            }
        }
    }

    public void refresh(Topic topic) {
        for (int i = 0; i < topicList.size(); i++) {
            if (TextUtils.equals(topicList.get(i).getId(), topic.getId())) {
                topicList.set(i, topic);
                topicGridAdapter.notifyItemChanged(i);
                break;
            }
        }

    }

    public void topicDelete(Topic topic) {
        for (int i = 0; i < topicList.size(); i++) {
            if (TextUtils.equals(topicList.get(i).getId(), topic.getId())) {
                topicList.remove(i);
                topicGridAdapter.notifyItemRemoved(i);
                topicGridAdapter.notifyItemRangeChanged(i, topicList.size() - i);
                break;
            }
        }
    }

    /**
     * 判断是否是游客
     *
     * @return
     */
    private boolean isTempUser() {
        if (TextUtils.equals(uId, loginUser.getuId()) && loginUser.getType() == Constant.USER_TYPE_TEMP) {
            return true;
        }
        return false;
    }

    public void setItemClickListener(ItemClickListener itemClickListener) {
        this.itemClickListener = itemClickListener;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        broadcastManager.unregisterReceiver(broadcastReceiver);
    }

    public interface ItemClickListener {
        void onItemClick(Topic topic);

    }

    public interface InteractionListener {

        void showLoading(boolean isShowProgressBar);
    }
}
